package com.aspect;

import com.bean.WebsiteVisitorApi;
import com.bean.anno.LogAnno;
import com.bean.anno.VisitAnno;
import com.mapper.repository.mysql.WebsiteVisitorApiRepository;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.awt.windows.WEmbeddedFrame;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

@Aspect
@Component
@Slf4j
public class VisitAspect {

    @Autowired
    private WebsiteVisitorApiRepository websiteVisitorApiRepository;

    //表示只要是加了@LoginAnno这个注解的方法，都会被拦截
    @Pointcut("@annotation(com.bean.anno.VisitAnno)")
    public void pointcut() {

    }

    @Around("pointcut()")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {


        MethodSignature signature = (MethodSignature) joinPoint.getSignature();//
        Method method = signature.getMethod();

        VisitAnno visitAnno = method.getAnnotation(VisitAnno.class);
        String apiName = visitAnno.apiName();
        boolean flag = visitAnno.flag();
        if(flag){
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            String addr = request.getRemoteAddr();
            String useragent = request.getHeader("User-Agent");

            WebsiteVisitorApi websiteVisitorApi = new WebsiteVisitorApi();
            websiteVisitorApi.setId(UUID.randomUUID().toString());
            websiteVisitorApi.setAddr(addr);
            websiteVisitorApi.setApiname(apiName);
            websiteVisitorApi.setUseragent(useragent);
            websiteVisitorApi.setCreatetime(LocalDateTime.now());
            websiteVisitorApiRepository.save(websiteVisitorApi);

        }


        Object result = null;
        try {
            result = joinPoint.proceed();//执行切点方法
            if(flag){
                log.info(apiName+"结果");
                log.info(result.toString());
            }
        } catch (Throwable e) {
            log.error(e.toString());
            throw e;
        }
        return result;
    }


}
